package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/olivere/elastic/v7"
)

var url = []string{"http://127.0.0.1:9200"}

type poem struct {
	Id        string `json:"id"`
	Auther    string `json:"auther"`
	Name      string `json:"name"`
	Content   string `json:"content"`
	Favourite int64  `json:"favourite"`
}

func main() {
	es, err := elastic.NewClient(elastic.SetURL(url...))
	if err != nil {
		panic(err)
	}
	if false {
		termQuery := elastic.NewTermQuery("auther", "李白")
		res, err := es.Search().Index("poems").Query(termQuery).Do(context.Background())
		if err != nil {
			panic(err)
		}
		if res.TotalHits() > 0 {
			for _, hit := range res.Hits.Hits {
				var p poem
				err = json.Unmarshal(hit.Source, &p)
				if err != nil {
					panic(err)
				}
				fmt.Printf("%#v\n", p)
			}
		}
	}
	if true {
		matchQuery := elastic.NewMatchQuery("content", "多少")
		res, err := es.Search().Index("poems").Query(matchQuery).Do(context.Background())
		if err != nil {
			panic(err)
		}
		if res.TotalHits() > 0 {
			for _, hit := range res.Hits.Hits {
				var p poem
				err = json.Unmarshal(hit.Source, &p)
				if err != nil {
					panic(err)
				}
				fmt.Printf("%#v\n", p)
			}
		}
	}
}
